package iabincatalog.parser;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 * This class is just a playground for JDOM API.
 */
public class CopyOfXmlParser {

	// Logger
	private static Logger logger = Logger.getLogger(CopyOfXmlParser.class);
	

	/**
	 * Run the tests.
	 */
	public static void main(String[] args) throws Exception 
	{
		logger.info("Creating XML");
		createXML();
		
		logger.info("Translating");
		translateToPortuguese();
		
		logger.info("Done");
	}
		
	/**
	 * Creates a simple XML file "my.xml".
	 * @throws Exception
	 */
	private static void createXML() throws Exception
	{
		// Prepare a new document
		Document doc = new Document();
		Element person = new Element("Person");		
		doc.setRootElement(person);
		
		// Insert elements
		Element name = new Element("Name");
		name.setText("John Jdom");
		person.addContent(name);
		
		Element age = new Element("Age");
		age.setText("20");
		person.addContent(age);
		
		// Create the my.xml file
		File file = new File("my.xml");
		FileOutputStream fileOut = new FileOutputStream(file);
		XMLOutputter out = new XMLOutputter();
		out.output(doc, fileOut);
	}
	
	/**
	 * Translate the "my.xml" recently created file to a portuguese version,
	 * "meu.xml" (and the respective tags also translated).
	 * @throws Exception
	 */
	private static void translateToPortuguese() throws Exception
	{
		// Open my.xml file to be parsed
		SAXBuilder builder = new SAXBuilder();
		builder.setValidation(false);
		builder.setIgnoringElementContentWhitespace(true);
		Document doc = builder.build(new File("my.xml"));
		
		// Get and edit its elements
		Element root = doc.getRootElement();
		root.setName("Pessoa");
		
		Element name = root.getChild("Name");
		name.setName("Nome");
		
		Element age = root.getChild("Age");
		age.setName("Idade");
		
		// Prepare a new document
		File file = new File("meu.xml");
		FileOutputStream fileOut = new FileOutputStream(file);
		XMLOutputter out = new XMLOutputter();
		out.output(doc, fileOut);
	}

}
